<template>
  <div class="m-dashboard">
    <div class="g-content pb-0">
      <x-form ref="formRef" v-model:model="form" inline wrap label-placement="left" size="small">
        <n-form-item label="账户ID">
          <n-input v-model:value="form.accountCode" size="small" placeholder="请输入账户ID" clearable></n-input>
        </n-form-item>
        <n-form-item label="账户名称">
          <n-input v-model:value="form.accountName" size="small" placeholder="请输入账户名称" clearable></n-input>
        </n-form-item>
        <n-form-item label="账户主体">
          <n-select v-model:value="form.mdmName" size="small" placeholder="请选择" :options="companyList" clearable />
        </n-form-item>
        <n-form-item label="余额情况">
          <n-select
            v-model:value="form.balanceStatus"
            size="small"
            placeholder="请选择"
            :options="balanceStatusList"
            clearable
          />
        </n-form-item>
        <n-space>
          <x-button size="small" type="primary" @click="handleSubmit">查询</x-button>
          <x-button size="small" @click="handleRefresh">重置</x-button>
        </n-space>
      </x-form>
    </div>
    <div class="g-content">
      <div>
        <x-data-table
          ref="tableRef"
          v-model:immediate="immediate"
          :params="paginationParams"
          :columns="columns"
          :scroll-x="TableScrollX"
          :row-key="(row) => row.id"
          :export-action="exportAction"
          :export-name-prefix="exportName"
          row-class-name="text-sm"
          max-height="infinite"
          @update:sorter="handleSorterChange"
        >
          <template #tableTitle>
            <div class="flex">
              <div style="flex: 1">
                <x-button v-auth="['腾讯广告3.0-添加账户']" type="primary" size="small" @click="navigatorAccount"
                  >添加账户</x-button
                >
              </div>
              <x-diy-column-draggable
                :key="diyColumnName"
                v-model:value="showColumnList"
                :button-size="'small'"
                :name="diyColumnName"
                :min="0"
                api="dictionary/columnList"
                :api-params="diyColumnParams"
                :default-value="columnDefaultValue"
              />
            </div>
          </template>
        </x-data-table>
      </div>
    </div>
    <AddDominantEdit v-if="modalAdd.show" :modal-data="modalAdd" @success="handleRefresh" />
  </div>
</template>

<script setup lang="ts">
  import { formatDate } from '@/utils'
  import { ref, computed, h, onMounted, reactive } from 'vue'
  import { XForm, XButton, XDataTable, XDiyColumnDraggable } from '@/components'
  import { NFormItem, NSelect, NText, NInput, NSpace, useMessage } from 'naive-ui'
  import AddDominantEdit from '@/views/advertising/components/AddDominantEdit.vue'
  import { useRouter } from 'vue-router'
  import { useStore } from '@/store'
  const router = useRouter()
  const store = useStore()
  const message = useMessage()
  const modalAdd = ref({
    show: false,
    type: 'add'
  })
  const props = defineProps({
    dateRange: {
      type: Array,
      default: () => [Date.parse(new Date()), Date.parse(new Date())]
    }
  })
  const getProps = reactive(props)
  const tableRef = ref(null)
  const formRef = ref(null)
  const form = ref({
    order: '',
    desc: null,
    accountCode: null,
    accountName: null,
    mdmName: null,
    balanceStatus: null
  })
  const balanceStatusList = ref([
    {
      label: '查看为0的账户',
      value: 0
    },
    {
      label: '查看不为0的账户',
      value: 1
    }
  ])
  const companyList = ref([])
  const immediate = ref(true)
  const diyColumnParams = ref({
    key: 'ACCOUNT_REPORT'
  })
  // 自定义列
  const showColumnList = ref([])
  const diyColumnName = computed(() => {
    return 'ADV_COLUMN'
  })
  const columnDefaultValue = ref(['account1'])
  const paginationParams = computed(() => {
    return {
      actions: 'intelligent/gdtAccountList',
      data: {
        ...form.value,
        dateRange: null,
        startDate: getProps.dateRange?.[0] ? formatDate(getProps.dateRange?.[0]) : null,
        endDate: getProps.dateRange?.[1] ? formatDate(getProps.dateRange?.[1]) : null,
        columns: showColumnList.value?.toString()
      }
    }
  })
  const exportAction = computed(() => 'intelligent/accountExport')
  const exportName = computed(() => {
    return `【账户】${formatDate(new Date(), 'yyyyMMddhhmmss')}`
  })
  const columns = computed(() => {
    const arr = [
      {
        title: '账户名称',
        key: 'accountName',
        width: 100,
        render(row: any) {
          return h(NSpace, { vertical: true }, () => [
            h(NText, {}, () => row.accountName),
            h(NText, {}, () => `ID：${row.accountCode}`),
            h(NText, {}, () => `广告主行业：${row.systemIndustryName || '-'}`)
          ])
        }
      },
      {
        title: '操作',
        width: 100,
        key: 'operator',
        render(row: any) {
          return h(NSpace, { vertical: true }, () => [
            h(XButton, { text: true, size: 'mini', type: 'primary', onClick: () => handleAd(row) }, () => '查看广告'),
            h(
              XButton,
              { text: true, size: 'mini', type: 'primary', onClick: () => handleMedia(row) },
              () => '查看创意'
            ),
            h(
              XButton,
              { text: true, size: 'mini', type: 'primary', onClick: () => handleCreate(row) },
              () => '创建广告'
            )
          ])
        }
      },
      {
        title: '账户日预算',
        key: 'dailyBudget',
        width: 100,
        render(row: any) {
          return row.dailyBudget ? row.dailyBudget : '不限'
        }
      },
      {
        title: '账户余额',
        key: 'accountBalance',
        sorter: true,
        width: 100,
        render(row: any) {
          return row.accountBalance ? row.accountBalance : '-'
        }
      },
      {
        title: '登录账户',
        key: 'loginName',
        width: 100
      },
      {
        title: '所属人员',
        key: 'ownerName',
        width: 100
      },
      {
        title: '曝光次数',
        key: 'viewCount',
        sorter: true,
        width: 100
      },
      {
        title: '曝光人数',
        key: 'viewUserCount',
        sorter: true,
        width: 100
      },
      {
        title: '点击次数',
        key: 'validClickCount',
        sorter: true,
        width: 100
      },
      {
        title: '点击人数',
        key: 'clickUserCount',
        sorter: true,
        width: 100
      },
      {
        title: '点击均价',
        key: 'cpc',
        sorter: true,
        width: 100
      },
      {
        title: '点击率',
        key: 'ctr',
        sorter: true,
        width: 80,
        render(row: any) {
          return row.ctr ? row.ctr + '%' : '-'
        }
      },
      {
        title: '花费',
        key: 'cost',
        sorter: true,
        width: 80
      },
      {
        title: '目标转化量',
        key: 'conversionsCount',
        sorter: true,
        width: 120,
        render(row: any) {
          return row.conversionsCount ? row.conversionsCount : '-'
        }
      },
      {
        title: '目标转化率',
        key: 'conversionsRate',
        sorter: true,
        width: 120,
        render(row: any) {
          return row.conversionsRate ? row.conversionsRate + '%' : '-'
        }
      },
      {
        title: '深度目标转化量',
        key: 'deepConversionsCount',
        sorter: true,
        width: 140
      },
      {
        title: '目标转化成本',
        key: 'conversionsCost',
        sorter: true,
        width: 120
      },
      {
        title: '深度转化成本',
        key: 'deepConversionsCost',
        sorter: true,
        width: 120
      },
      {
        title: '深度目标转化率',
        key: 'deepConversionsRate',
        sorter: true,
        width: 140,
        render(row: any) {
          return row.deepConversionsRate ? row.deepConversionsRate + '%' : '-'
        }
      },
      {
        title: '下单率',
        key: 'orderRate',
        sorter: true,
        width: 100,
        render(row: any) {
          return row.orderRate ? row.orderRate + '%' : '-'
        }
      },
      {
        title: '下单次数',
        width: 120,
        sorter: true,
        key: 'orderPv'
      },
      {
        title: '下单ROI',
        width: 100,
        sorter: true,
        key: 'orderRoi'
      },
      {
        title: '下单金额',
        width: 100,
        sorter: true,
        key: 'orderAmount'
      },
      {
        title: '下单成本',
        width: 100,
        sorter: true,
        key: 'orderCost'
      }
    ]
    const sortArr: (
      | { title: string; key: string; width: number; sorter?: undefined }
      | {
          title: string
          width: number
          key: string
          render(row: any): VNode<RendererNode, RendererElement, { [key: string]: any }>
          sorter?: undefined
        }
      | { title: string; key: string; sorter: boolean; width: number; render(row: any): any }
      | { title: string; key: string; sorter: boolean; width: number }
      | { title: string; key: string; width: number; render(row: any): string; sorter?: undefined }
    )[] = []
    showColumnList.value.forEach((item) => {
      arr.forEach((item2) => {
        if (item === item2.key) {
          sortArr.push(item2)
        }
      })
    })
    return sortArr.filter((item) => ['operator', ...showColumnList.value].includes(item.key))
  })
  const TableScrollX = computed(() => {
    let x = 20
    columns.value.forEach((item) => {
      if (item.type === 'expand') {
        x += 30
      }
      if (item.type === 'selection') {
        x += 30
      }
      if (item.width) {
        x += item.width
      }
    })
    return x
  })

  onMounted(() => {
    getCompanyList()
  })

  function handleSorterChange(options: { order: string | number | boolean; columnKey: string }) {
    const sortKey: any = {
      descend: 'desc',
      ascend: 'asc'
    }
    form.value.order = options?.columnKey
    form.value.desc = options.order ? sortKey[options.order] : null
    handleSubmit()
  }
  const handleSubmit = () => {
    immediate.value = true
  }
  const handleRefresh = () => {
    formRef.value.resetFields()
    handleSubmit()
  }
  const getCompanyList = () => {
    store
      .dispatch('system/mediaAccountMdmNameList', {
        pageSize: 10000
      })
      .then(({ data }) => {
        const list: { value: any; label: any }[] = []
        data.forEach((item: any) => {
          list.push({
            value: item,
            label: item
          })
        })
        companyList.value = list
      })
  }
  const navigatorAccount = () => {
    router.push({
      name: 'Adv'
    })
  }

  const handleCreate = (row: any) => {
    router.push({
      name: 'AdsCreate',
      query: {
        accountCode: row.accountCode,
        mdmName: row.mdmName
      }
    })
  }
  const handleAd = (row: any) => {
    router.push({
      name: 'Dashboard',
      query: {
        accountCode: row.accountCode,
        templateType: 2
      }
    })
  }
  const handleMedia = (row: any) => {
    router.push({
      name: 'Dashboard',
      query: {
        accountCode: row.accountCode,
        templateType: 3
      }
    })
  }
</script>

<style lang="scss" scoped></style>
